#include "ImageChatService.h"
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QEventLoop>
#include <QDebug>

// 构造函数
ImageChatService::ImageChatService(QObject *parent)
    : QObject(parent), manager(new QNetworkAccessManager(this))
{
}

// 主要的聊天功能函数
QString ImageChatService::chatWithImage(const QString &imagePath, const QString &prompt,
                                        const QString &url, const QString &apiKey,
                                        const QString &modelName)
{
    // 将图片编码为base64
    QString base64Image = encodeImage(imagePath);
    
    // 构建JSON请求体
    QJsonObject payload;
    payload["model"] = modelName;
    
    QJsonArray messages;
    QJsonObject message;
    message["role"] = "user";
    
    QJsonArray content;
    QJsonObject textContent;
    textContent["type"] = "text";
    textContent["text"] = prompt;
    content.append(textContent);
    
    QJsonObject imageContent;
    imageContent["type"] = "image_url";
    QJsonObject imageUrl;
    imageUrl["url"] = QString("data:image/jpeg;base64,%1").arg(base64Image);
    imageContent["image_url"] = imageUrl;
    content.append(imageContent);
    
    message["content"] = content;
    messages.append(message);
    payload["messages"] = messages;
    
    QJsonObject options;
    options["temperature"] = 0;
    options["seed"] = 123;
    payload["options"] = options;

    // 设置网络请求
    QNetworkRequest request{QUrl{url}};
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setRawHeader("Authorization", QString("Bearer %1").arg(apiKey).toUtf8());
    
    // 发送POST请求
    QNetworkReply *reply = manager->post(request, QJsonDocument(payload).toJson());
    
    // 等待响应
    QEventLoop loop;
    connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();
    
    // 处理响应
    if (reply->error() == QNetworkReply::NoError) {
        QJsonDocument response = QJsonDocument::fromJson(reply->readAll());
        QString content = response.object()["choices"].toArray().first().toObject()["message"].toObject()["content"].toString();
        reply->deleteLater();
        qDebug() << imagePath << " 回答:" << content;
        return content;
    } else {
        QString errorMessage = QString("错误: %1").arg(reply->errorString());
        reply->deleteLater();
        qDebug() << imagePath << " 错误:" << errorMessage;
        return errorMessage;
    }
}

// 将图片编码为base64字符串
QString ImageChatService::encodeImage(const QString &imagePath)
{
    QFile file(imagePath);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "无法打开图片文件";
        return QString();
    }
    return file.readAll().toBase64();
}
